
  <template>
    <div ref="cell"></div>
  </template>

<script>
import Vue from 'vue';
export default {
  name: 'TableCell',
  props: {
    row: Object,
    column: Object,
    naturalIndex: String
  },
  methods: {
    compile() {
      if (this.column.render) {
        // const $parent = this.column.context ? this.column.context : this.$parent.$parent.$parent;
        const $parent = this.$parent.$parent.$parent.$parent;
        const template = this.column.render(this.row, this.column, this.naturalIndex);
        const cell = document.createElement('div');
        cell.innerHTML = template;
        this.$el.innerHTML = '';
        let methods = {};
        const methodskey = this.column.methodskey || [];
        Object.keys($parent).forEach(key => {
          const func = $parent[key];
          // Dranein: 从外部去传入需要加载的method
          const hasmethodsKey = methodskey.length && methodskey.indexOf(String(key)) > -1;
          if (typeof (func) === 'function' && (func.name === 'boundFn' || func.name === 'n' || hasmethodsKey)) {
            methods[key] = func;
          }
        });
        const res = Vue.compile(cell.outerHTML);

        // // 获取父组件使用的局部 component
        const components = {};
        Object.getOwnPropertyNames($parent.$options.components).forEach(item => {
          components[item] = $parent.$options.components[item];
        });
        const component = new Vue({
          render: res.render,
          staticRenderFns: res.staticRenderFns,
          methods: methods,
          data() {
            return $parent._data;
          },
          components: components
        });
        component.row = this.row;
        component.column = this.column;

        const Cell = component.$mount();
        this.$refs.cell.appendChild(Cell.$el);
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.compile();
    });
  },
  watch: {
    naturalIndex() {
      this.compile();
    },
    row: {
      handler: function () {
        this.compile();
      },
      deep: true
    }
  }
};
</script>
